package com.apobates.forum.trident.controller.admin;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.apobates.forum.core.api.service.AlbumPictureService;
import com.apobates.forum.core.api.service.AlbumService;
import com.apobates.forum.core.api.service.TopicService;
import com.apobates.forum.core.entity.Album;
import com.apobates.forum.core.entity.AlbumPicture;
import com.apobates.forum.core.entity.Topic;
import com.apobates.forum.trident.controller.form.AlbumPictureForum;
import com.apobates.forum.trident.exception.ResourceNotFoundException;
import com.apobates.forum.trident.fileupload.ImageStorageExecutor;
import com.apobates.forum.utils.Commons;
import com.apobates.forum.utils.FrontPageURL;
import com.apobates.forum.utils.TipMessage;
import com.apobates.forum.utils.persistence.Page;
import com.apobates.forum.utils.persistence.PageRequest;
import com.apobates.forum.utils.persistence.Pageable;
/**
 * 话题像册控制器
 * 
 * @author xiaofanku
 * @since 20190407
 */
@Controller
@RequestMapping(value = "/admin/topic/album")
public class AdminAlbumController {
	@Autowired
	private AlbumService albumService;
	@Autowired
	private AlbumPictureService albumPictureService;
	@Autowired
	private TopicService topicService;
	@Autowired
	private ImageStorageExecutor imageStorageExecutor;
	@Value("${site.pageSize}")
	private int pageSize;
	
	// 所有的话题像册列表
	@GetMapping(path="/")
	public String listPage(
			@RequestParam(value = "p", required = false, defaultValue = "1") int page, 
			HttpServletRequest request, 
			Model model) {
		FrontPageURL fpbuild = new FrontPageURL(request.getContextPath() + "/admin/topic/album/").addPageSize("number", pageSize);
		Pageable pr = new PageRequest(page, fpbuild.getPageSize());
		Page<Album> rs = albumService.getAll(pr);
		model.addAttribute("rs", rs.getResult().collect(Collectors.toList()));
		model.addAttribute("pageData", pr.toData(fpbuild, rs.getTotalElements()));
		return "admin/album/index";
	}
	
	// 话题的图片列表
	@GetMapping(path="/picture")
	public String getAlbumPicture(
			@RequestParam("topic")long topicId,
			HttpServletRequest request,
			Model model){
		//像册->图片
		Optional<Album> topicAlbum = albumService.getByTopic(topicId);
		if(!topicAlbum.isPresent()){
			return "admin/album_picture/index";
		}
		Album album = topicAlbum.get();
		model.addAttribute("album", album);
		
		List<AlbumPicture> pictures = new ArrayList<>();
		pictures.addAll(albumPictureService.getAll(album.getId()).collect(Collectors.toList()));
		model.addAttribute("rs", pictures);
		return "admin/album_picture/index";
	}
	
	// 为话题像册添加图片 | 话题没像册时album=0
	@GetMapping(path="/picture/add")
	public String addAlbumPictureForm(
			@RequestParam("topic")long topicId,
			@RequestParam(value = "album", required = false, defaultValue = "0")long topicAlbumId,
			HttpServletRequest request,
			Model model){
		topicService.get(topicId).orElseThrow(()->new ResourceNotFoundException("话题不存在或暂时无法访问"));
		AlbumPictureForum form = new AlbumPictureForum();
		form.setAlbumId(topicAlbumId+"");
		form.setTopicId(topicId+"");
		form.setCaption(""); 
		form.setStatus(true);
		form.setToken(Commons.randomAlphaNumeric(8));
		model.addAttribute("form", form);
		return "admin/album_picture/add";
	}
	@PostMapping(path="/picture/add")
	public String addAlbumPictureAction(
			@ModelAttribute("form")AlbumPictureForum form, 
			HttpServletRequest request,
			Model model){
		Topic topic = topicService.get(form.getLongTopicId()).orElseThrow(()->new ResourceNotFoundException("话题不存在或暂时无法访问"));
		//
		String imageAddr = null;
		//------------------------------------------------------------编码图标图片的地址
		imageAddr = form.getEncodePictureAddr(imageStorageExecutor);
		//------------------------------------------------------------
		long albumId = form.getLongAlbumId(); boolean symbol=false;
		if(albumId>0){
			symbol = albumPictureService.create(albumId, imageAddr, form.getCaption(), form.getIntegerRanking(), form.getBooleanStatus()).isPresent();
		}else{
			long data = albumService.create(imageAddr, form.getCaption(), form.getBooleanStatus(), topic);
			symbol = data > 0;
		}
		if(symbol){
			return "redirect:/admin/topic/album/picture?topic="+form.getTopicId();
		}
		model.addAttribute("errors", "添加图片操作失败");
		form.setToken(Commons.randomAlphaNumeric(8));
		model.addAttribute("form", form);
		return "admin/album_picture/add";
	}
	// 设置某图片为指定话题像册的封面
	@PostMapping(path="/cover", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public TipMessage setupTopicAlbumCoverAction(
			@RequestParam("album")long topicAlbumId,
			@RequestParam("cover")long coverPictureId,
			HttpServletRequest request, 
			Model model){
		try{
			Optional<Boolean> data = albumService.editCover(topicAlbumId, coverPictureId);
			if(data.isPresent()){
				return TipMessage.ofSuccess("封面图片设置成功");
			}
		}catch(IllegalStateException e){
			return TipMessage.ofError(e.getMessage());
		}
		return TipMessage.ofError("操作失败");
	}
}
